package com.example.demo.service.impl;

import com.example.demo.dao.PaymentRecordDAO;
import com.example.demo.dataobject.PaymentRecordDO;
import com.example.demo.model.PaymentRecord;
import com.example.demo.param.PaymentRecordQueryParam;
import com.example.demo.service.PaymentRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class PaymentRecordServiceImpl implements PaymentRecordService {
    @Autowired
    private PaymentRecordDAO paymentRecordDAO;
    @Override
    public PaymentRecord save(PaymentRecord paymentRecord) {
        if (paymentRecord == null) {
            return null;
        }
        PaymentRecordDO paymentRecordDO = paymentRecord.toDO();
        if (StringUtils.isEmpty(paymentRecord.getId())) {
            paymentRecordDO.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            int insertSize = paymentRecordDAO.insert(paymentRecordDO);
            if (insertSize < 1) {
                return null;
            }
            paymentRecord.setId(paymentRecordDO.getId());
            return paymentRecord;
        } else {
            int updateSize = paymentRecordDAO.update(paymentRecordDO);
            if (updateSize < 1) {
                return null;
            }
            return paymentRecord;
        }
    }

    @Override
    public List<PaymentRecord> query(PaymentRecordQueryParam queryParam) {
        List<PaymentRecord> paymentRecords = new ArrayList<>();
        List<PaymentRecordDO> paymentRecordDOS = paymentRecordDAO.select(queryParam);
        if (CollectionUtils.isEmpty(paymentRecordDOS)) {
            return paymentRecords;
        }
        paymentRecordDOS.forEach(paymentRecordDO ->{
            paymentRecords.add(paymentRecordDO.toModel());
        });
        return paymentRecords;
    }

    @Override
    public PaymentRecord update(PaymentRecord paymentRecord) {
        paymentRecordDAO.update(paymentRecord.toDO());
        return paymentRecord;
    }


}
